#pragma once
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptValue>
#include <QVariant>
#include "js.h"
using namespace std;
class view: public QObject{
    Q_OBJECT
    table* viewTable;
    view(table* viewTable){this->viewTable=viewTable;}
public:

    static view* viewmanager;

    static view* getViewManager(){
        if(viewmanager==nullptr){
            viewmanager=new view (table::loadFile("views"));
            viewmanager->viewTable->setSystemManage();
        }
        return viewmanager;
    }

    table* getViewTable(){
        return this->viewTable;
    }

    string viewNameToUserViewName(const string& viewName){
        return tableManager::getcurOperatUser()+":"+viewName;
    }

    JSVM* getViewJSVM()
    {
        JSVM* VM=AddJSVM();
        QScriptValue viewmanager=VM->newQObject(view::viewmanager);
        VM->globalObject().setProperty("viewmanager",viewmanager);
        return VM;
    }

    table* strDateToTable(const string& viewName,string& to_do){
        vector<col*> cols;
        vector<IndexType> inds;
        const auto& tp=IO::get_empty_table_cols(to_do);
        cols=get<0>(tp);
        inds=get<1>(tp);
        IO::put_single_block_data(cols,to_do);
        return new table(viewName,cols,{},true,inds);
    }

    Q_INVOKABLE void addView(const QString& viewName,const QString& viewCode){
        Basic* ts_1=typeHelper::typehelper->strToBasic(viewNameToUserViewName(viewName.toStdString()),STR);
        Basic* ts_2=typeHelper::typehelper->strToBasic(viewCode.toStdString(),STR);
        this->viewTable->add({ts_1,ts_2});
        this->viewTable->updateFile();
    }

    Q_INVOKABLE bool delView(const QString& viewName){
        vector<int> viewIndex=this->viewTable->find({"(x=='"+viewNameToUserViewName(viewName.toStdString())+"')",""});
        if(viewIndex.empty()==true){
            return false;
        }
        this->viewTable->del(viewIndex);
        this->viewTable->updateFile();
        return true;
    }

    Q_INVOKABLE table* evalView(const QString& viewName){
        vector<int> viewIndex=this->viewTable->find({"(x=='"+viewNameToUserViewName(viewName.toStdString())+"')",""});
        if(viewIndex.empty()==true){
            throw string("The specified view was not found");
        }
        string viewCode=this->viewTable->getCol("viewCode")->getData(viewIndex)[0]->toStr();
        QString mistake;
        QVariant varResult=JSEval(QString::fromStdString(viewCode),"eval",&mistake,getViewJSVM());
        if(varResult==NULL){
            throw string("Wrong view code");
        }
        string strData=varResult.toString().toStdString();
        return strDateToTable(viewName.toStdString(),strData);
    }
};
